//
//  GYCustomHUD.m
//  GYCustomHUD
//
//  Created by zgy on 2025/5/6.
//

#import "GYCustomHUD.h"
#import "GYSpinnerView.h"
#import "GYActivityIndicatorView.h"
#import "YYCategoriesMacro.h"

@implementation GYCustomHUD

static GYCustomHUD *__currentHUD = nil;
static UIView *__containerView;

static UILabel *__label;
static GYSpinnerView *__spinner;


+ (instancetype)showHUDWithType:(GYHUDType)type message:(NSString *)message hideAfter:(NSTimeInterval)duration
{
    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    //    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    UIWindow *keyWindow = nil;
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive) {
                keyWindow = scene.windows.firstObject;
                break;
            }
        }
    } else {
        keyWindow = [UIApplication sharedApplication].keyWindow;
    }
    
#pragma clang diagnostic pop
    
    if (!keyWindow) return nil;
    
    if (__currentHUD) {
        [self setupUIWithKeyWindow:keyWindow hudType:type message:message hideAfter:duration];
        return __currentHUD;
    }

    
    
    GYCustomHUD *hud = [[GYCustomHUD alloc] initWithFrame:keyWindow.bounds];
    hud.backgroundColor = [UIColor clearColor];
    [keyWindow addSubview:hud];
    __currentHUD = hud;
    
    
    
    UIView *containerView = [[UIView alloc] init];
    containerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];
    containerView.layer.cornerRadius = 5.0;
    containerView.clipsToBounds = YES;
    [hud addSubview:containerView];
    __containerView = containerView;
    
    
    __label = [[UILabel alloc] init];
    
    [self setupUIWithKeyWindow:keyWindow hudType:type message:message hideAfter:duration];
    
    
    return hud;
}


+ (void)setupUIWithKeyWindow:(UIWindow *)keyWindow hudType:(GYHUDType)type message:(NSString *)message hideAfter:(NSTimeInterval)duration
{
    GYSpinnerView *loadingView;
    switch (type) {
        case GYHUDTypeLoading:
        {
            if (!__spinner) {
                __spinner = [[GYSpinnerView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
            }
            
            __spinner.hidden = NO;
            loadingView = __spinner;
        }
            break;
        case GYHUDTypeMessage:
            loadingView = nil;
            __spinner.hidden = YES;
            break;
    }
    
    
    UILabel *label = __label;
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    
    
    
    CGFloat maxWidth = keyWindow.bounds.size.width - 80;
    CGSize maxSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    
    CGSize labelSize = [label sizeThatFits:maxSize];
    labelSize.width = MIN(labelSize.width, maxWidth);
    labelSize.height = MIN(labelSize.height, keyWindow.bounds.size.height - 80);
    
    
    label.frame = CGRectMake(0, 0, labelSize.width, labelSize.height);
    
    
    
    CGFloat containerWidth = MAX(labelSize.width + 40, 100);
    CGFloat containerHeight = labelSize.height + (loadingView ? 80 : 20);
    __containerView.frame = CGRectMake(0, 0, containerWidth, containerHeight);
    __containerView.center = __currentHUD.center;
    
    
    if (loadingView) {
        __containerView.layer.cornerRadius = 5.0;
        [__containerView addSubview:loadingView];
        loadingView.center = CGPointMake(__containerView.frame.size.width / 2, 35);
        [__containerView addSubview:loadingView];
        
        if (labelSize.height == 0) {
            loadingView.center = CGPointMake(__containerView.frame.size.width / 2, __containerView.frame.size.height / 2);
        }
        
        label.font = [UIFont systemFontOfSize:13];
        label.center = CGPointMake(__containerView.frame.size.width / 2, __containerView.frame.size.height - 25);
    }else {
        
        label.center = CGPointMake(__containerView.frame.size.width / 2, __containerView.frame.size.height / 2);
        
        // 如果只有一行  圆角为高度一半
        if (labelSize.height < 22) {
            __containerView.layer.cornerRadius = containerHeight * 0.5;
        }
    }
    [__containerView addSubview:label];
    
    
    if (duration > 0) {
        [self cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayDismiss) object:nil];
        [self performSelector:@selector(delayDismiss) withObject:nil afterDelay:duration];
    }else {
        [self cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayDismiss) object:nil];
    }
}

+ (void)delayDismiss
{
    [self hideHUD];
}



+ (void)showLoading
{
    dispatch_async_on_main_queue(^{
        [self showLoadingWithText:@"正在加载"];
    });
}


+ (void)showLoadingWithText:(NSString *)text
{
    dispatch_async_on_main_queue(^{
        [self showHUDWithType:GYHUDTypeLoading message:text hideAfter:0];
    });
}


+ (void)showMessage:(NSString *)msg
{
    dispatch_async_on_main_queue(^{
        [self showHUDWithType:GYHUDTypeMessage message:msg hideAfter:2];
    });
}

+ (void)showMessage:(NSString *)msg hideAfter:(NSTimeInterval)duration
{
    dispatch_async_on_main_queue(^{
        [self showHUDWithType:GYHUDTypeMessage message:msg hideAfter:duration];
    });
}

+ (void)hideHUD
{
    dispatch_async_on_main_queue(^{
        if (__currentHUD) {
            [__currentHUD removeFromSuperview];
            __currentHUD = nil;
            __containerView = nil;
            
            __label = nil;
            __spinner = nil;
        }
    });
}


+ (void)hideHUDWithDelay:(NSTimeInterval)duration
{
    dispatch_async_on_main_queue(^{
        if (duration > 0) {
            [self cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayDismiss) object:nil];
            [self performSelector:@selector(delayDismiss) withObject:nil afterDelay:duration];
        }else {
            [self delayDismiss];
        }
    });
}




//- (void)dealloc
//{
//    NSLog(@"GYCustomHUD 释放了");
//}
@end
